package com.cetcs.kmga.dataManager.util.socket;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Created by XingWen on 2016/12/23.
 */
@Component
public class WebsocketEndPoint extends TextWebSocketHandler{
    private static final Logger logger = LoggerFactory.getLogger(WebsocketEndPoint.class);

    @Autowired
    private MsgService msgService;

    @Override
    protected void handleTextMessage(WebSocketSession session,
                                     TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");
        session.sendMessage(returnMessage);
    }

    /**
     * @Description :　建立连接后
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception{

        UserSocket userSocket = (UserSocket)session.getAttributes().get("SESSION_USER");

        //boss
        //test
        //集成登录后，去掉该段代码
        userSocket.setUserId("1");

        if(null != userSocket){
            userSocket.setWebSocketSession(session);
            if(WSSessionLocalCache.exists(userSocket.getUserId())){
                WSSessionLocalCache.remove(userSocket.getUserId());
            }
            WSSessionLocalCache.put(userSocket.getUserId(), userSocket);
            msgService.afterConnectionEstablished(userSocket.getUserId());
        }
        logger.info("socket成功建立连接...");
        super.afterConnectionEstablished(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session,CloseStatus status) throws Exception{
        UserSocket userSocket = (UserSocket)session.getAttributes().get("SESSION_USER");
        if(null != userSocket){
            WSSessionLocalCache.remove(userSocket.getUserId());
        }
        logger.info("socket成功关闭连接...");
        super.afterConnectionClosed(session, status);
    }
}
